﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;
using System.ComponentModel;
using TM.QWeibo.Client.Helper;
using Microsoft.Phone.Shell;

namespace TM.QWeibo.Client
{
    public partial class MainPage : PhoneApplicationPage
    {
        //查新线程
        private BackgroundWorker BackgroundCheckWorker { get; set; }

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            this.ApplicationBar.BackgroundColor = (Color)App.Current.Resources["ApplicationBarBackgroundColor"];
            Dispatcher.BeginInvoke(() =>
            {
                if (NavigationService.CanGoBack)
                {
                    NavigationService.RemoveBackEntry();
                }

                homeTimeLine.Selected = SelectTweet;
                mentionsTimeLine.Selected = SelectTweet;
                privateMessage.Selected = SelectMessage;

                homeTimeLine.GotLastest = ClearHomeCount;
                mentionsTimeLine.GotLastest = ClearMentionsCount;
                privateMessage.GotLastest = ClearMessageCount;

                homeTimeLine.MenuItemClick = MenuItemClick;
                mentionsTimeLine.MenuItemClick = MenuItemClick;
            });
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            tbAccountName.Text =string.Format("腾讯微博 {0}", AppSetting.AccountNickName);
            try
            {
                Dal.Friends.Instance.DownloadedIdolListDispose();
                this.ApplicationBar.IsVisible = App.IsShowAdd;
                if (!App.IsShowAdd)
                {
                    homeAd.Show(()=> Dispatcher.BeginInvoke(() =>
                                                                {
                                                                    this.ApplicationBar.IsVisible = true;
                                                                }));
                }

                if (AppSetting.CheckUpdateSecondSpan > 0)
                {
                    if (BackgroundCheckWorker == null)
                    {
                        BackgroundCheckWorker = new BackgroundWorker();
                        BackgroundCheckWorker.WorkerSupportsCancellation = true;
                        BackgroundCheckWorker.DoWork+=BackgroundCheckThead_DoWork;
                        BackgroundCheckWorker.RunWorkerCompleted+=BackgroundCheckThead_RunWorkerCompleted;
                    }
                    BackgroundCheckWorker.RunWorkerAsync();
                }
            }
            catch
            {
                
            }
        }

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);
            try
            {
                if (BackgroundCheckWorker != null)
                {
                    BackgroundCheckWorker.CancelAsync();
                    BackgroundCheckWorker.DoWork -= BackgroundCheckThead_DoWork;
                    BackgroundCheckWorker.RunWorkerCompleted -= BackgroundCheckThead_RunWorkerCompleted;
                    BackgroundCheckWorker = null;
                }
            }
            catch
            {
                
            }

        }

        ///// <summary>
        ///// 查看资料
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void btnProfile_Click(object sender, EventArgs e)
        //{
        //    NavigationService.Navigate(new Uri(string.Format("/Profile.xaml?{0}={1}", AppSetting.UserNameParameterKey, AppSetting.AccountName), UriKind.Relative));
        //}

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(string.Format("/Tweet/Add.xaml"), UriKind.Relative));
        }

        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReload_Click(object sender, EventArgs e)
        {
            switch (PivotMain.SelectedIndex)
            {
                case 0: homeTimeLine.Reset(); break;
                case 1: mentionsTimeLine.Reset(); break;
                case 2: privateMessage.Reset(); break;
            }
        }

        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled=PivotMain.SelectedIndex!=3;
            switch (PivotMain.SelectedIndex)
            {
                case 0: homeTimeLine.Init(BeforeLoading, AfterLoaded); break;
                case 1: mentionsTimeLine.Init(BeforeLoading, AfterLoaded); break;
                case 2: privateMessage.Init(BeforeLoading, AfterLoaded); break;
            }
        }
        /// <summary>
        /// 加载数据前显示loading状态
        /// </summary>
        private void BeforeLoading() {
            Dispatcher.BeginInvoke(()=>performanceBar.IsIndeterminate=true);
        }

        /// <summary>
        /// 加载数据后隐藏loading状态，显示相关信息
        /// </summary>
        private void AfterLoaded(object tweets)
        {
            Dispatcher.BeginInvoke(() => {
                performanceBar.IsIndeterminate = false;
            });
        }
        /// <summary>
        /// 选中微博，跳转到详细页
        /// </summary>
        /// <param name="t"></param>
        private void SelectTweet(SDK.Objects.Tweet t) {
            if (t != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri(string.Format("/Tweet/Detail.xaml?{0}={1}", AppSetting.TweetIdParameterKey, t.Id), UriKind.Relative)));
            }
        }

        /// <summary>
        /// 选中私信，跳转到对话
        /// </summary>
        /// <param name="t"></param>
        private void SelectMessage(SDK.Objects.Tweet t)
        {
            if (t != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri(string.Format("/Message/Dialog.xaml?{0}={1}", AppSetting.UserNameParameterKey, t.Name), UriKind.Relative)));
            }
        }

        /// <summary>
        /// 设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mSetting_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(string.Format("/Setting.xaml"), UriKind.Relative));
        }


        /// <summary>
        /// 注销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mLogout_Click(object sender, EventArgs e)
        {
            var rs = MessageBox.Show("确定注销吗？\r\n注销后将会自动退出，重启程序继续使用。", "注销", MessageBoxButton.OKCancel);
            if (rs == MessageBoxResult.OK)
            {
                Common.OauthHelper.Logout();
                Common.OauthHelper.IsVerified = false;
                AppSetting.IsScheduledAgent = false;
                AppSetting.CheckUpdateSecondSpan = 0;
                //NavigationService.Navigate(new Uri(string.Format("/Oauth.xaml"), UriKind.Relative));
                App.Quit();
            }
        }

        private void mProfile_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(string.Format("/Profile.xaml?{0}={1}", AppSetting.UserNameParameterKey, AppSetting.AccountName), UriKind.Relative));
        }


        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!NavigationService.CanGoBack)
            {
                var b = true;
                if (AppSetting.IsExitConfirm)
                {
                    var rs = MessageBox.Show("确定退出吗？", "提示", MessageBoxButton.OKCancel);
                    b = rs != MessageBoxResult.Cancel;
                }
                if (b)
                {
                    App.Quit();
                }
                else {
                    e.Cancel = true;
                }
            }
        }

        #region 后台进程检查更新

        /// <summary>
        /// 检查后台数据更新
        /// </summary>
        public void CheckUpdateCountThread()
        {

            if (AppSetting.CheckUpdateSecondSpan > 0)
            {
                Dal.Status.Instance.Check(CheckUpdateEnd);
            }
        }

        public void CheckUpdateEnd(SDK.Objects.UpdateCount count)
        {
            UpdateUiCount(count);
            if (AppSetting.CheckUpdateSecondSpan > 0 && !BackgroundCheckWorker.IsBusy)
            {
                Thread.Sleep(AppSetting.CheckUpdateSecondSpan);

                BackgroundCheckWorker.RunWorkerAsync();
            }
        }

        /// <summary>
        /// 更新界面的显示
        /// </summary>
        /// <param name="count"></param>
        public void UpdateUiCount(SDK.Objects.UpdateCount count)
        {
            try
            {
                if (count == null) {
                    return;
                }
                Dispatcher.BeginInvoke(() =>
                {
                    imgTweetCount.Visibility = count.Home > 0 ? Visibility.Visible : Visibility.Collapsed;
                    imgCommentCount.Visibility = count.Mentions > 0 ? Visibility.Visible : Visibility.Collapsed;
                    imgMessageCount.Visibility = count.PrivateMessage > 0 ? Visibility.Visible : Visibility.Collapsed;
                    imgFanxCount.Visibility = count.Fans > 0 ? Visibility.Visible : Visibility.Collapsed;

                    tbTweetCount.Visibility = count.Home > 0 ? Visibility.Visible : Visibility.Collapsed;
                    tbCommentCount.Visibility = count.Mentions > 0 ? Visibility.Visible : Visibility.Collapsed;
                    tbMessageCount.Visibility = count.PrivateMessage > 0 ? Visibility.Visible : Visibility.Collapsed;
                    tbFanxCount.Visibility = count.Fans > 0 ? Visibility.Visible : Visibility.Collapsed;

                    if (count.Home > 0) { tbTweetCount.Text = count.Home.ToString(); }
                    if (count.Mentions > 0) { tbCommentCount.Text = count.Mentions.ToString(); }
                    if (count.PrivateMessage > 0) { tbMessageCount.Text = count.PrivateMessage.ToString(); }
                    if (count.Fans > 0) { tbFanxCount.Text = count.Fans.ToString(); }

                });
            }
            catch
            {
                
            }
        }

        public void ClearHomeCount()
        {
            ClearCount(SDK.Objects.UpdateCount.ECountType.Home);
            ClearCount(SDK.Objects.UpdateCount.ECountType.Create);
        }

        public void ClearMentionsCount()
        {
            ClearCount(SDK.Objects.UpdateCount.ECountType.Mentions);
        }

        public void ClearMessageCount()
        {
            ClearCount(SDK.Objects.UpdateCount.ECountType.PrivateMessage);
        }

        private void ClearCount(SDK.Objects.UpdateCount.ECountType type)
        {
            Dal.Status.Instance.Check(type, (rs) =>
            {
                UpdateUiCount(rs);
            });
        }


        public void BackgroundCheckThead_DoWork(object sender, DoWorkEventArgs e)
        {
            if (!BackgroundCheckWorker.CancellationPending)
            {
                CheckUpdateCountThread();
            }
        }

        public void BackgroundCheckThead_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
            
            //if (AppSetting.CheckUpdateSecondSpan > 0 && !BackgroundCheckThead.IsBusy) {
            //    Thread.Sleep(AppSetting.CheckUpdateSecondSpan);
            //    BackgroundCheckThead.RunWorkerAsync();
            //}
        }

        #endregion

        private void mExit_Click(object sender, EventArgs e)
        {
            var b = true;
            if (AppSetting.IsExitConfirm)
            {
                var rs = MessageBox.Show("确定退出吗？", "提示", MessageBoxButton.OKCancel);
                b = rs != MessageBoxResult.Cancel;
            }
            if (b)
            {
                App.Quit();
            }
        }

        /// <summary>
        /// 控件弹出菜单服务
        /// </summary>
        /// <param name="t"></param>
        /// <param name="act"></param>
        private void MenuItemClick(SDK.Objects.Tweet t,EMenuItemAction act) {
            if (act == EMenuItemAction.Reply)
            {
                Common.Isolated.Set(Helper.IsolatedHelper.TargetTweetKey, t);
                NavigationService.Navigate(new Uri(string.Format("/Tweet/Add.xaml?{0}={1}", AppSetting.AddTweetTypeParameterKey, Helper.EAddTweetType.Reply.GetHashCode()), UriKind.Relative));
            }
            else if (act == EMenuItemAction.ReAdd)
            {
                Common.Isolated.Set(Helper.IsolatedHelper.TargetTweetKey, t);
                NavigationService.Navigate(new Uri(string.Format("/Tweet/Add.xaml?{0}={1}", AppSetting.AddTweetTypeParameterKey, Helper.EAddTweetType.ReAdd.GetHashCode()), UriKind.Relative));
            }
            else if (act == EMenuItemAction.Favorite)
            {

                Dal.Tweet.Instance.AddFavorite(t.Id, (rs) =>
                {
                    (new Helper.MessageBoxHelper()).Show("收藏" + (rs ? "成功" : "失败"), "提示", this.LayoutRoot);
                });

            }
            else if(act==EMenuItemAction.Comment){
                Common.Isolated.Set(Helper.IsolatedHelper.TargetTweetKey, t);
                NavigationService.Navigate(new Uri(string.Format("/Tweet/Add.xaml?{0}={1}", AppSetting.AddTweetTypeParameterKey, Helper.EAddTweetType.Comment.GetHashCode()), UriKind.Relative));
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Search.xaml", UriKind.Relative));
        }

        private void mApps_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(string.Format("/TopApps.xaml"), UriKind.Relative));
        }

        private void imgTweetCount_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (PivotMain.SelectedIndex != 0)
            {
                PivotMain.SelectedIndex = 0;
            }
        }

        private void imgCommentCount_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (PivotMain.SelectedIndex !=1)
            {
                PivotMain.SelectedIndex = 1;
            }
        }

        private void imgMessageCount_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (PivotMain.SelectedIndex != 2)
            {
                PivotMain.SelectedIndex = 2;
            }
        }

        private void imgFanxCount_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            mProfile_Click(null,null);
        }
    }
}